using Super;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class UIItemList : MonoBehaviour
{
	// Start is called before the first frame update
	private bool hasInit = false;
	public GameObject itemPrefab;
	public List<GameObject> hideList = new List<GameObject>();
	private GOPool pool;
	public Dictionary<int, Transform> itemDict = new Dictionary<int, Transform>();
	private Action<Transform, int> refreshAction;
	public List<object> dataList = new List<object>();
	private Action<Transform, int, object> refreshDataAction;


	public void Awake()
	{
		Init();
	}

	public void Init()
	{
		if (hasInit) return;
		hasInit = true;

		pool = new GOPool(itemPrefab, transform);
		foreach (var item in hideList)
		{
			item.SetActive(false);
		}
	}

	public void SetItemNum(int num, Action<Transform, int> action)
	{
		Init();
		itemDict.Clear();
		pool.RecycleAll();
		GameObject itemClone;
		refreshAction = action;
		for (int i = 0; i < num; i++)
		{
			itemClone = pool.Get();
			itemClone.transform.SetAsLastSibling();

			itemDict[i] = itemClone.transform;
			action(itemClone.transform, i);
		}
		itemPrefab.SetActive(false);
	}

	public void SetItemNum(int num, List<object> dataList, Action<Transform, int, object> action)
	{
		Init();
		itemDict.Clear();
		pool.RecycleAll();
		GameObject itemClone;
		this.dataList = dataList;
		refreshDataAction = action;
		for (int i = 0; i < num; i++)
		{
			itemClone = pool.Get();
			itemClone.transform.SetAsLastSibling();

			itemDict[i] = itemClone.transform;
			action(itemClone.transform, i, dataList[i]);
		}
		itemPrefab.SetActive(false);
	}

	public void Refresh()
	{
		foreach (var item in itemDict)
		{
			if (refreshAction != null)
				refreshAction(item.Value, item.Key);
			else if (refreshDataAction != null)
			{
				object data = dataList[item.Key];
				refreshDataAction(item.Value, item.Key, data);
			}
		}
	}

	public void RefreshItem(int index)
	{
		Transform tf = GetItemByIndex(index);
		if (refreshAction != null)
			refreshAction(tf, index);
		else if (refreshDataAction != null)
		{
			object data = dataList[index];
			refreshDataAction(tf, index, data);
		}
	}

	public List<Transform> GetItemList()
	{
		return itemDict.OrderBy(source => source.Key).Select(source => source.Value).ToList();
	}

	public Transform GetItemByIndex(int index)
	{
		return itemDict[index];
	}

	public int GetItemCount()
	{
		return itemDict.Count;
	}
}
